"""
核心配置管理模块
使用 Pydantic Settings 管理环境变量和配置文件
"""

import os
from functools import lru_cache
from typing import Any, Dict, List, Optional

import yaml
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """应用配置类"""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="allow",
    )

    # 应用配置
    APP_NAME: str = Field(default="ZBlog Python API", description="应用名称")
    APP_VERSION: str = Field(default="1.0.0", description="应用版本")
    DEBUG: bool = Field(default=False, description="调试模式")
    HOST: str = Field(default="0.0.0.0", description="服务器主机")
    PORT: int = Field(default=8000, description="服务器端口")
    ENVIRONMENT: str = Field(default="development", description="运行环境")

    # 数据库配置
    DATABASE_URL: str = Field(
        default="mysql+pymysql://root:password@localhost:3306/zblog",
        description="数据库连接URL",
    )
    DATABASE_ECHO: bool = Field(default=False, description="是否打印SQL")

    # JWT 配置
    SECRET_KEY: str = Field(
        default="your-secret-key-change-in-production", description="JWT密钥"
    )
    ALGORITHM: str = Field(default="HS256", description="加密算法")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(default=30, description="Token过期时间")

    # CORS 配置
    CORS_ORIGINS: str = Field(
        default="http://localhost:5173,http://localhost:3000,http://localhost:8080,http://127.0.0.1:5173,http://127.0.0.1:3000,http://127.0.0.1:8080,http://localhost:8000,http://127.0.0.1:8000", 
        description="允许的来源"
    )

    # MiniMax 配置（文生图）
    MINIMAX_API_KEY: Optional[str] = Field(default=None, description="MiniMax API密钥")
    MINIMAX_MODEL: str = Field(default="image-01", description="MiniMax 文生图模型")
    MINIMAX_DEBUG_MODE: bool = Field(default=True, description="MiniMax 调试模式（True=使用模拟数据，False=使用真实API）")

    # AI 默认配置
    AI_REQUEST_TIMEOUT: int = Field(default=120, description="AI请求超时时间（秒）")
    AI_MAX_RETRIES: int = Field(default=2, description="最大重试次数")
    AI_RETRY_DELAY: float = Field(default=2.0, description="重试延迟（秒）")

    # 日志配置
    LOG_LEVEL: str = Field(default="INFO", description="日志级别")
    LOG_FILE: str = Field(default="logs/app.log", description="日志文件路径")

    @field_validator("CORS_ORIGINS")
    @classmethod
    def assemble_cors_origins(cls, v: str) -> List[str]:
        """解析CORS来源"""
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",") if origin.strip()]
        return v

    @property
    def cors_origins_list(self) -> List[str]:
        """获取CORS来源列表"""
        if isinstance(self.CORS_ORIGINS, str):
            return [origin.strip() for origin in self.CORS_ORIGINS.split(",")]
        return self.CORS_ORIGINS


class ConfigManager:
    """配置管理器，负责加载和管理 YAML 配置文件"""

    def __init__(self, config_dir: str = "config"):
        self.config_dir = config_dir
        self._app_config: Optional[Dict[str, Any]] = None
        self._ai_config: Optional[Dict[str, Any]] = None

    def load_yaml(self, filename: str) -> Dict[str, Any]:
        """加载 YAML 配置文件"""
        file_path = os.path.join(self.config_dir, filename)
        if not os.path.exists(file_path):
            return {}

        with open(file_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f) or {}

    @property
    def app_config(self) -> Dict[str, Any]:
        """获取应用配置"""
        if self._app_config is None:
            self._app_config = self.load_yaml("config.yaml")
        return self._app_config

    @property
    def ai_config(self) -> Dict[str, Any]:
        """获取AI配置"""
        if self._ai_config is None:
            self._ai_config = self.load_yaml("ai_models.yaml")
        return self._ai_config

    def get_environment_config(self, environment: str) -> Dict[str, Any]:
        """获取特定环境的配置"""
        return self.app_config.get(environment, {})

    def get_ai_provider_config(self, provider: str) -> Dict[str, Any]:
        """获取特定AI提供商的配置"""
        providers = self.ai_config.get("providers", {})
        return providers.get(provider, {})

    def get_ai_model_config(self, provider: str, model: str) -> Dict[str, Any]:
        """获取特定AI模型的配置"""
        provider_config = self.get_ai_provider_config(provider)
        models = provider_config.get("models", {})
        return models.get(model, {})

    def get_ai_defaults(self) -> Dict[str, Any]:
        """获取AI默认配置"""
        return self.ai_config.get("defaults", {})

    def get_ai_features(self, provider: str) -> Dict[str, bool]:
        """获取AI提供商支持的功能特性"""
        features = self.ai_config.get("features", {})
        return features.get(provider, {})

    def get_ai_pricing(self, provider: str, model: str) -> Dict[str, float]:
        """获取AI模型定价"""
        pricing = self.ai_config.get("pricing", {})
        provider_pricing = pricing.get(provider, {})
        return provider_pricing.get(model, {})


@lru_cache
def get_settings() -> Settings:
    """获取应用设置（单例模式）"""
    return Settings()


@lru_cache
def get_config_manager() -> ConfigManager:
    """获取配置管理器（单例模式）"""
    return ConfigManager()


# 导出配置实例
settings = get_settings()
config_manager = get_config_manager()

